<?php 
namespace Home\Controller;
class CartController extends HomeController {
    public function index(){
        $email = $_SESSION['email'];
        $data = M()->table('dota2_user')->join('dota2_carts')->join('dota2_goods')->join('dota2_goodsimg')->where(' email="'.$email.'" and u_id = cu_id and cg_id = g_id and g_id = gi_g_id and face = 1 and up = 1')->select();
        $sum = 0;
        foreach($data as $v){
            $sum = $sum + $v['price']*$v['cg_num'];
        }
        $this->assign('sum',$sum);
        $this->assign('cartlist',$data);
        $coin = M()->table('dota2_user')->join('dota2_user_info')->where('email ="'.$email.'" and u_id = ui_id')->select();
        $this->assign('coin',$coin[0]['dotacoin']);
        $this->display();
    }

    public function addCart(){
        $email = $_SESSION['email'];
        if(empty($email)){
            echo json_encode('false');
        }else{
            $uid = M('user')->where('email="'.$email.'"')->select();
            $uid = $uid[0]['u_id'];
            $carts = M("carts");
            $status = $carts->where('cg_id = "'.$_POST['gid'].'" and cu_id ="'.$uid.'"')->select();
            if($status == false){
                $data['cg_id'] = $_POST['gid'];
                $data['cu_id'] = $uid;
                $data['cg_num'] = '1';
                $carts->add($data);
            }else{
                $cid = $status[0]['c_id'];
                $carts->where('c_id ="'.$cid.'"')->setInc('cg_num',1);
            }
            echo json_encode('true');
        }
    }

    public function delCart(){
        $cid = I('post.cid');
        M('carts')->delete($cid);
    }

    public function editCart(){
        $num = $_POST['num'];
        $gid = $_POST['gid'];
        $model = M('carts');
        $data['cg_num'] = $num;
        $model->where('cg_id="'.$gid.'"')->save($data);
        $email = $_SESSION['email'];
        $list = M()->table('dota2_user')->join('dota2_carts')->join('dota2_goods')->where(' email="'.$email.'" and u_id = cu_id and cg_id = g_id')->select();
        $sss = 0;
        foreach($list as $v){
            $sss = $sss + $v['price']*$v['cg_num'];
        }
        echo json_encode($sss);
    }
}